package com.example.emergencyattempt01.fragement.user_fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.Pack_DePackUtil;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import com.example.emergencyattempt01.adapter.HistoryTab_ListViewAdapter;
import com.example.emergencyattempt01.adapter.IngTab_ListViewAdapter;
import com.example.emergencyattempt01.adapter.ReturnBook_Pager_Adapter;
import com.example.emergencyattempt01.user.Student;
import com.example.emergencyattempt01.user.User;
import com.viewpagerindicator.TabPageIndicator;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class Return_Book_Fragment extends Fragment {
    ViewPager returnBookPager;
    TabPageIndicator indicator;
    List<View> viewList=new ArrayList<>();
    List<String> titleList=new ArrayList<>();
    ReturnBook_Pager_Adapter pager_adapter;


    View ingTab;
    View historyTab;

    // INGTAB
    ListView ingListView;
    List<Map<String,Object>> ingList=new ArrayList<>();
    IngTab_ListViewAdapter ingTab_listViewAdapter;
    Handler handlerForIngTab=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case ING_LOAD_SUCCESS:
                    canCount=true;
                    ingTab_listViewAdapter.notifyDataSetChanged();
                    Toast.makeText(ingTab.getContext(),"加载成功",Toast.LENGTH_SHORT).show();
                    break;
                case ING_LOAD_FAIL:
                    Toast.makeText(ingTab.getContext(),"加载失败",Toast.LENGTH_SHORT).show();
                    break;
                    
                case  ING_NOT_FOUND:
                    Toast.makeText(ingTab.getContext(),"当前没有在借图书",Toast.LENGTH_SHORT).show();
                    break;
                    
                case COUNT_DOWN:
                    ingTab_listViewAdapter.notifyDataSetChanged();
                    break;
                    
                case COUNT_ZERO:
                    ingTab_listViewAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    final int ING_LOAD_SUCCESS=0x001;
    final int ING_LOAD_FAIL=0x002;
    final int ING_NOT_FOUND=0x003;
    
    final int COUNT_DOWN=0x004;
    final int COUNT_ZERO=0x005;
    
    boolean canCount;
    

    // HISTORYTAB
    SwipeRefreshLayout historyRefresher;
    ListView historyListView;
    List<Map<String,Object>> historyList=new ArrayList<>();
    HistoryTab_ListViewAdapter historyTab_listViewAdapter;
    Handler handlerForHistoryTab=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case HISTORY_LOAD_SUCCESS:
                   historyTab_listViewAdapter.notifyDataSetChanged();
                    break;

                case HISTORY_LOAD_FAIL:
                    break;

                case  HISTORY_NOT_FOUND:
                    break;
                case HISTORY_REFRESH_SUCCESS:
                    historyTab_listViewAdapter.notifyDataSetChanged();
                    Toast.makeText(historyTab.getContext(),"刷新成功",Toast.LENGTH_SHORT).show();
                    historyRefresher.setRefreshing(false);
                    break;
                case HISTORY_REFRESH_FAIL:
                    Toast.makeText(historyTab.getContext(),"刷新失败",Toast.LENGTH_SHORT).show();
                    historyRefresher.setRefreshing(false);
                    break;
                    
                case HISTORY_REFRESH_NOT_FOUND:
                    Toast.makeText(historyTab.getContext(),"当前没有归还任何图书",Toast.LENGTH_SHORT).show();
                    historyRefresher.setRefreshing(false);
                    break;
            }
        }
    };
    final int HISTORY_LOAD_SUCCESS=0x006;
    final int HISTORY_LOAD_FAIL=0x007;
    final int HISTORY_NOT_FOUND=0x008;

    final int HISTORY_REFRESH_SUCCESS=0x009;
    final int HISTORY_REFRESH_FAIL=0x010;
    final int HISTORY_REFRESH_NOT_FOUND=0x011;
    

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.return_book_fragment_layout,null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initUser();
        initPage();

        // 分别对两个Tab进行布局，逻辑编写
        // ingTab
        setIngTab();
        // historyTab
        setHistoryTab();


    }

    private void setHistoryTab() {
      // 初始化listView，适配器
        historyListView=historyTab.findViewById(R.id.history_listView);
        historyTab_listViewAdapter=new HistoryTab_ListViewAdapter(historyList,historyTab.getContext());
        historyListView.setAdapter(historyTab_listViewAdapter);
        loadHistoryMessage();
        setRefresh();
    }

    private void setRefresh() {
        historyRefresher=historyTab.findViewById(R.id.history_tab_refresher);
        historyRefresher.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Thread()
                {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject=new JSONObject();
                            jsonObject.put("uid",Student.getInstance().getUid());
                            String toServer=String.valueOf(jsonObject);
                            ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/find_my_history");
                            int code=serverMessage.getRespondCode();
                            if(code==200)
                            {
                                if(Pack_DePackUtil.dePackBorrowAhead((String)serverMessage.getFromServer(),historyList)) // 找到了
                                {
                                    Message message=new Message();
                                    message.what=HISTORY_REFRESH_SUCCESS;
                                    handlerForHistoryTab.sendMessage(message);
                                }
                                else// 没找到
                                {
                                    Message message=new Message();
                                    message.what=HISTORY_REFRESH_NOT_FOUND;
                                    handlerForHistoryTab.sendMessage(message);
                                }

                            }
                            else {
                                Message message=new Message();
                                message.what=HISTORY_REFRESH_FAIL;
                                handlerForHistoryTab.sendMessage(message);
                            }

                        }catch (JSONException e){e.printStackTrace();}
                        catch (IOException e){e.printStackTrace();
                            Message message=new Message();
                            message.what=HISTORY_REFRESH_FAIL;
                            handlerForHistoryTab.sendMessage(message);}
                    }
                }.start();
            }
        });

    }

    private void loadHistoryMessage() {
        new Thread()
        {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("uid",Student.getInstance().getUid());
                    String toServer=String.valueOf(jsonObject);
                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/find_my_history");
                    int code=serverMessage.getRespondCode();
                    if(code==200)
                    {
                        if(Pack_DePackUtil.dePackBorrowAhead((String)serverMessage.getFromServer(),historyList)) // 找到了
                        {
                            Message message=new Message();
                            message.what=HISTORY_LOAD_SUCCESS;
                            handlerForHistoryTab.sendMessage(message);
                        }
                        else// 没找到
                        {
                            Message message=new Message();
                            message.what=HISTORY_NOT_FOUND;
                            handlerForHistoryTab.sendMessage(message);
                        }

                    }
                    else {
                        Message message=new Message();
                        message.what=HISTORY_LOAD_FAIL;
                        handlerForHistoryTab.sendMessage(message);
                    }

                }catch (JSONException e){e.printStackTrace();}
                catch (IOException e){e.printStackTrace();
                    Message message=new Message();
                    message.what=HISTORY_LOAD_FAIL;
                    handlerForHistoryTab.sendMessage(message);}
            }
        }.start();
    }

    private void setIngTab() {
     // 初始化listView，适配器
        ingListView=ingTab.findViewById(R.id.ing_listView);
        ingTab_listViewAdapter=new IngTab_ListViewAdapter(ingList,ingTab.getContext());
        ingListView.setAdapter(ingTab_listViewAdapter);
        
        loadIngMessage();
    }

    private void loadIngMessage() {
        // 此线程用于加载信息
        new Thread()
        {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("uid",Student.getInstance().getUid());
                    String toServer=String.valueOf(jsonObject);
                    ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/find_my_borrowing");
                    int code=serverMessage.getRespondCode();
                    if(code==200)
                    {
                       if(Pack_DePackUtil.dePackBorrowAhead((String)serverMessage.getFromServer(),ingList)) // 找到了
                       {
                           Message message=new Message();
                           message.what=ING_LOAD_SUCCESS;
                           handlerForIngTab.sendMessage(message);
                       }
                       else// 没找到
                       {
                           Message message=new Message();
                           message.what=ING_NOT_FOUND;
                           handlerForIngTab.sendMessage(message);
                       }

                    }
                    else {
                        Message message=new Message();
                        message.what=ING_LOAD_FAIL;
                        handlerForIngTab.sendMessage(message);
                    }
                    
                }catch (JSONException e){e.printStackTrace();}
                catch (IOException e){e.printStackTrace();
                    Message message=new Message();
                    message.what=ING_LOAD_FAIL;
                    handlerForIngTab.sendMessage(message);}
            }
        }.start();
        // 此线程用于维持计时器
        new Thread()
        {
            @Override
            public void run() {
                while(true)
                {
                    if(canCount)
                    {
                        try {
                            Thread.sleep(1000);
                        }catch (InterruptedException e){e.printStackTrace();}
                        for(int i=0;i<ingList.size();i++)
                        {
                            long last=(long)ingList.get(i).get("lastTime")-1000l;
                            if(last/1000>=0)// 描述大于零，不是毫秒数大于零
                            {
                                ingList.get(i).put("lastTime",last);
                                Message message=new Message();
                                message.what=COUNT_DOWN;
                                handlerForIngTab.sendMessage(message);
                            }
                            else
                            {
                                ingList.get(i).put("lastTime",0l);
                                Message message=new Message();
                                message.what=COUNT_ZERO;
                                message.obj=i;
                                handlerForIngTab.sendMessage(message);
                            }
                        }
                    }

                }
            }
        }.start();
    }

    private void initPage() {
        // 初始化pager
        returnBookPager=getActivity().findViewById(R.id.return_book_pager);
        // 初始化indicator
        indicator=getActivity().findViewById(R.id.return_book_indicator);
        // 初始化两个list
        // viewList
        ingTab=LayoutInflater.from(getActivity()).inflate(R.layout.st_ing_tab_layout,null);
        historyTab=LayoutInflater.from(getActivity()).inflate(R.layout.st_history_tab_layout,null);
        viewList.add(ingTab);
        viewList.add(historyTab);
        // titleList
        titleList.add("在借中");
        titleList.add("历史记录");
        // 建立关联
        pager_adapter=new ReturnBook_Pager_Adapter(getActivity(),viewList,titleList);
        returnBookPager.setAdapter(pager_adapter);
        indicator.setViewPager(returnBookPager);
    }
    private void initUser() {
       User student= Student.getInstance();
       User.initUser(getActivity(),student);
    }
}
